package com.yuanqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.dto.SalesOrderDTO;
import com.yuanqi.dto.SalesOrderQueryDTO;
import com.yuanqi.pojo.Customer;
import com.yuanqi.pojo.SalesOrder;
import com.yuanqi.pojo.SalesOrderItem;
import com.yuanqi.pojo.Sku;
import com.yuanqi.pojo.Product;
import com.yuanqi.service.CustomerService;
import com.yuanqi.service.SalesOrderItemService;
import com.yuanqi.service.SalesOrderService;
import com.yuanqi.service.SkuService;
import com.yuanqi.service.ProductService;
import com.yuanqi.mapper.SalesOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.yuanqi.dto.SalesOrderListDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// PDFBox imports
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
* @author LENOVO
* @description 针对表【sales_order(销售订单)】的数据库操作Service实现
* @createDate 2025-08-28 15:23:08
*/
@Service
public class SalesOrderServiceImpl extends ServiceImpl<SalesOrderMapper, SalesOrder>
    implements SalesOrderService{

    private static final Logger log = LoggerFactory.getLogger(SalesOrderServiceImpl.class);

    @Autowired
    private SalesOrderItemService salesOrderItemService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProductService productService;

    @Override
    public SalesOrderDTO createSalesOrder(SalesOrderDTO salesOrderDTO) {
        return createOrUpdateOrder(salesOrderDTO);
    }

    @Override
    public boolean updateSalesOrder(SalesOrderDTO salesOrderDTO) {
        try {
            createOrUpdateOrder(salesOrderDTO);
            return true;
        } catch (Exception e) {
            log.error("更新销售订单失败", e);
            return false;
        }
    }



    @Override
    public SalesOrderDTO createOrUpdateOrder(SalesOrderDTO salesOrderDTO) {
        try {
            SalesOrder order = salesOrderDTO.getOrder();

            // 设置基本信息
            if (order.getId() == null) {
                // 新增订单
                order.setCreatedAt(new Date());
                order.setStatus(0); // 草稿状态

                // 生成订单编号
                if (order.getSoCode() == null || order.getSoCode().isEmpty()) {
                    order.setSoCode(generateOrderCode());
                }
                if (order.getOrderCode() == null || order.getOrderCode().isEmpty()) {
                    order.setOrderCode(order.getSoCode());
                }
            }

            order.setUpdatedAt(new Date());

            // 设置客户信息
            if (order.getCustomerId() != null) {
                Customer customer = customerService.getById(order.getCustomerId());
                if (customer != null) {
                    order.setCustomerName(customer.getCustomerName());
                    if (order.getContactPhone() == null) {
                        order.setContactPhone(customer.getPhone());
                    }
                    if (order.getShippingAddress() == null) {
                        order.setShippingAddress(customer.getShippingAddress());
                    }
                }
            }

            // 设置日期信息
            Date now = new Date();
            if (order.getOrderDate() == null) {
                order.setOrderDate(order.getSaleDate() != null ? order.getSaleDate() : now);
            }
            if (order.getDeliveryDate() == null) {
                order.setDeliveryDate(order.getExpectedShipDate() != null ? order.getExpectedShipDate() : now);
            }

            // 设置总金额（兼容旧版本数据库）
            if (salesOrderDTO.getTotalAmount() != null) {
                order.setTotalAmount(salesOrderDTO.getTotalAmount());
            } else {
                // 如果没有传入总金额，设置为0
                order.setTotalAmount(BigDecimal.ZERO);
            }

            // 设置税率和税额（兼容旧版本数据库）
            if (order.getTaxRate() == null) {
                order.setTaxRate(new BigDecimal("0.13")); // 默认税率13%
            }
            if (order.getTotalAmount() != null && order.getTaxRate() != null) {
                // 计算税额：总金额 * 税率
                order.setTaxAmount(order.getTotalAmount().multiply(order.getTaxRate()));
            } else {
                order.setTaxAmount(BigDecimal.ZERO);
            }

            // 设置默认值
            if (order.getCurrency() == null) {
                order.setCurrency("CNY");
            }
            if (order.getTaxIncluded() == null) {
                order.setTaxIncluded("Y");
            }

            // 保存订单主表
            boolean success;
            if (order.getId() == null) {
                success = save(order);
            } else {
                success = updateById(order);
            }

            if (!success) {
                throw new RuntimeException("保存订单失败");
            }

            // 处理订单明细
            if (salesOrderDTO.getItems() != null && !salesOrderDTO.getItems().isEmpty()) {
                // 删除原有明细
                QueryWrapper<SalesOrderItem> deleteWrapper = new QueryWrapper<>();
                deleteWrapper.eq("so_id", order.getId());
                salesOrderItemService.remove(deleteWrapper);

                // 保存新明细
                for (int i = 0; i < salesOrderDTO.getItems().size(); i++) {
                    SalesOrderItem item = salesOrderDTO.getItems().get(i);
                    item.setSoId(order.getId());
                    item.setLineNo(i + 1);

                    // 处理临时SKU ID
                    log.info("处理订单明细项: skuId={}, productId={}", item.getSkuId(), item.getProductId());
                    
                    if (item.getSkuId() != null && item.getSkuId().toString().startsWith("temp_")) {
                        log.info("处理临时SKU ID: {}", item.getSkuId());
                        
                        // 临时SKU，需要根据productId查找真实SKU
                        if (item.getProductId() != null) {
                            // 根据productId查找默认SKU
                            List<Sku> existingSkus = skuService.list(new LambdaQueryWrapper<Sku>()
                                .eq(Sku::getProductId, item.getProductId())
                                .eq(Sku::getStatus, 1));
                            
                            log.info("找到现有SKU数量: {}", existingSkus.size());
                            
                            if (!existingSkus.isEmpty()) {
                                // 如果已存在SKU，使用第一个可用的
                                Long realSkuId = existingSkus.get(0).getId();
                                item.setSkuId(realSkuId.toString());
                                log.info("使用现有SKU: {}", realSkuId);
                            } else {
                                // 如果不存在SKU，创建一个新的
                                Sku newSku = new Sku();
                                newSku.setProductId(item.getProductId());
                                newSku.setSkuCode("AUTO_" + System.currentTimeMillis() + "_" + i);
                                newSku.setUnitId(1L); // 默认单位ID
                                newSku.setConversionRate(BigDecimal.ONE);
                                newSku.setStatus(1);
                                newSku.setCreatedAt(new Date());
                                newSku.setUpdatedAt(new Date());
                                
                                boolean skuSaved = skuService.save(newSku);
                                if (skuSaved && newSku.getId() != null) {
                                    Long realSkuId = newSku.getId();
                                    item.setSkuId(realSkuId.toString());
                                    log.info("创建新SKU成功: {}", realSkuId);
                                } else {
                                    log.error("创建SKU失败");
                                    throw new RuntimeException("创建SKU失败");
                                }
                            }
                        } else {
                            log.error("临时SKU ID {} 缺少对应的productId", item.getSkuId());
                            throw new RuntimeException("临时SKU ID需要对应的productId");
                        }
                    } else if (item.getSkuId() != null) {
                        // 检查SKU是否存在
                        Sku sku = skuService.getById(Long.valueOf(item.getSkuId()));
                        if (sku == null) {
                            log.error("SKU ID {} 不存在", item.getSkuId());
                            throw new RuntimeException("SKU ID " + item.getSkuId() + " 不存在");
                        }
                    } else {
                        log.error("SKU ID 为 null，无法处理");
                        throw new RuntimeException("SKU ID 不能为 null");
                    }
                    
                    log.info("最终SKU ID: {}", item.getSkuId());

                    // 计算行金额
                    if (item.getQty() != null && item.getPrice() != null) {
                        item.setAmount(item.getQty().multiply(item.getPrice()));
                    }

                    // 设置默认值
                    if (item.getTaxRate() == null) {
                        item.setTaxRate(new BigDecimal("0.13"));
                    }
                    if (item.getAllocatedQty() == null) {
                        item.setAllocatedQty(BigDecimal.ZERO);
                    }
                    if (item.getShippedQty() == null) {
                        item.setShippedQty(BigDecimal.ZERO);
                    }

                    salesOrderItemService.save(item);
                }
            }

            // 重新查询并返回
            return getOrderById(order.getId());

        } catch (Exception e) {
            log.error("创建或更新订单失败", e);
            throw new RuntimeException("创建或更新订单失败: " + e.getMessage());
        }
    }

    @Override
    public SalesOrderDTO getOrderById(Long orderId) {
        try {
            // 查询订单主表
            SalesOrder order = getById(orderId);
            if (order == null) {
                throw new RuntimeException("订单不存在");
            }

            // 查询订单明细
            QueryWrapper<SalesOrderItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("so_id", orderId);
            List<SalesOrderItem> items = salesOrderItemService.list(itemWrapper);

            // 构建DTO
            SalesOrderDTO dto = new SalesOrderDTO();
            dto.setOrder(order);
            dto.setItems(items);

            // 设置扁平字段
            dto.setSoCode(order.getSoCode());
            dto.setOrderCode(order.getOrderCode());
            dto.setOrderDate(order.getOrderDate());
            dto.setDeliveryDate(order.getDeliveryDate());
            dto.setTotalAmount(order.getTotalAmount());
            dto.setTaxRate(order.getTaxRate());
            dto.setTaxAmount(order.getTaxAmount());
            dto.setCreatedAt(order.getCreatedAt());
            dto.setStatus(order.getStatus());
            dto.setContactPhone(order.getContactPhone());
            dto.setRegion(order.getRegion());
            dto.setShippingAddress(order.getShippingAddress());
            dto.setSalesRep(order.getSalesRep());
            dto.setRespPhone(order.getRespPhone());
            dto.setSaleDate(order.getSaleDate());

            return dto;
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            throw new RuntimeException("获取订单详情失败: " + e.getMessage());
        }
    }

    @Override
    public SalesOrderDTO getSalesOrderDetail(Long orderId) {
        // 获取订单基本信息
        SalesOrder order = getById(orderId);
        if (order == null) {
            return null;
        }

        // 获取订单明细
        LambdaQueryWrapper<SalesOrderItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SalesOrderItem::getSoId, orderId);
        List<SalesOrderItem> items = salesOrderItemService.list(wrapper);

        // 填充商品信息
        for (SalesOrderItem item : items) {
            System.err.println(item);
            if (item.getProductId() != null) {
                // 根据productId查询商品信息
                Product product = productService.getById(item.getProductId());

                if (product != null) {
                    item.setProductName(product.getProductName());
                } else {
                    item.setProductName("商品" + item.getProductId());
                }

                // 根据skuId查询SKU信息
                if (item.getSkuId() != null) {
                    Sku sku = skuService.getById(Long.valueOf(item.getSkuId()));
                    if (sku != null) {
                        item.setSkuCode(sku.getSkuCode());
                    } else {
                        item.setSkuCode("SKU" + item.getSkuId());
                    }
                } else {
                    item.setSkuCode("");
                }
            }
        }

        // 获取客户信息
        Customer customer = customerService.getById(order.getCustomerId());

        // 构建DTO
        SalesOrderDTO dto = new SalesOrderDTO();
        dto.setOrder(order);
        dto.setItems(items);
        dto.setCustomerName(customer != null ? customer.getCustomerName() : "");
        dto.setCustomerPhone(customer != null ? customer.getPhone() : "");
        // 扁平字段
        dto.setSoCode(order.getSoCode());
        dto.setOrderCode(order.getOrderCode());
        dto.setCustomerName(order.getCustomerName());
        dto.setOrderDate(order.getOrderDate());
        dto.setDeliveryDate(order.getDeliveryDate());
        dto.setTotalAmount(order.getTotalAmount());
        dto.setTaxRate(order.getTaxRate());
        dto.setTaxAmount(order.getTaxAmount());
        dto.setCreatedAt(order.getCreatedAt());
        dto.setStatus(order.getStatus());
        dto.setContactPhone(order.getContactPhone());
        dto.setRegion(order.getRegion());
        dto.setShippingAddress(order.getShippingAddress());
        dto.setSalesRep(order.getSalesRep());
        dto.setRespPhone(order.getRespPhone());
        dto.setSaleDate(order.getSaleDate());

        // 计算总金额和总数量（若行金额为空则兜底计算）
        calculateOrderAmount(dto);

        return dto;
    }

    @Override
    public IPage<SalesOrderDTO> pageSalesOrders(SalesOrderQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<SalesOrder> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(queryDTO.getSoCode())) {
            wrapper.like(SalesOrder::getSoCode, queryDTO.getSoCode());
        }

        if (queryDTO.getCustomerId() != null) {
            wrapper.eq(SalesOrder::getCustomerId, queryDTO.getCustomerId());
        }

        if (StringUtils.hasText(queryDTO.getCustomerName())) {
            List<Long> customerIds = customerService
                    .list(new LambdaQueryWrapper<Customer>().like(Customer::getCustomerName, queryDTO.getCustomerName()))
                    .stream().map(Customer::getId).collect(Collectors.toList());
            if (customerIds.isEmpty()) {
                // 无匹配客户，直接返回空页
                return new Page<>(queryDTO.getPageNo(), queryDTO.getPageSize());
            }
            wrapper.in(SalesOrder::getCustomerId, customerIds);
        }

        if (queryDTO.getStatus() != null) {
            wrapper.eq(SalesOrder::getStatus, queryDTO.getStatus());
        }

        if (queryDTO.getStartDate() != null) {
            wrapper.ge(SalesOrder::getCreatedAt, queryDTO.getStartDate());
        }

        if (queryDTO.getEndDate() != null) {
            wrapper.le(SalesOrder::getCreatedAt, queryDTO.getEndDate());
        }

        // 排序
        if ("asc".equalsIgnoreCase(queryDTO.getSortDirection())) {
            wrapper.orderByAsc(SalesOrder::getCreatedAt);
        } else {
            wrapper.orderByDesc(SalesOrder::getCreatedAt);
        }

        // 分页查询
        Page<SalesOrder> page = new Page<>(queryDTO.getPageNo(), queryDTO.getPageSize());
        IPage<SalesOrder> orderPage = page(page, wrapper);

        // 转换为DTO
        IPage<SalesOrderDTO> dtoPage = new Page<>();
        dtoPage.setCurrent(orderPage.getCurrent());
        dtoPage.setSize(orderPage.getSize());
        dtoPage.setTotal(orderPage.getTotal());
        dtoPage.setPages(orderPage.getPages());

        List<SalesOrderDTO> dtoList = orderPage.getRecords().stream()
                .map(order -> {
                    SalesOrderDTO dto = new SalesOrderDTO();
                    dto.setOrder(order);
                    // 获取客户信息
                    Customer c = customerService.getById(order.getCustomerId());
                    dto.setCustomerName(c != null ? c.getCustomerName() : "");
                    dto.setCustomerPhone(c != null ? c.getPhone() : "");
                    // 扁平字段
                    dto.setSoCode(order.getSoCode());
                    dto.setOrderCode(order.getOrderCode());
                    dto.setCustomerName(order.getCustomerName());
                    dto.setOrderDate(order.getOrderDate());
                    dto.setDeliveryDate(order.getDeliveryDate());
                    dto.setTotalAmount(order.getTotalAmount());
                    dto.setCreatedAt(order.getCreatedAt());
                    dto.setStatus(order.getStatus());
                    dto.setContactPhone(order.getContactPhone());
                    dto.setRegion(order.getRegion());
                    dto.setShippingAddress(order.getShippingAddress());
                    dto.setSalesRep(order.getSalesRep());
                    dto.setRespPhone(order.getRespPhone());
                    dto.setSaleDate(order.getSaleDate());

                    // 运行时汇总金额与数量
                    List<SalesOrderItem> items = salesOrderItemService.list(new LambdaQueryWrapper<SalesOrderItem>().eq(SalesOrderItem::getSoId, order.getId()));
                    if (items != null && !items.isEmpty()) {
                        SalesOrderDTO tmp = new SalesOrderDTO();
                        tmp.setItems(items);
                        calculateOrderAmount(tmp);
                        dto.setTotalAmount(tmp.getTotalAmount());
                        dto.setTotalQuantity(tmp.getTotalQuantity());
                    }
                    return dto;
                })
                .collect(java.util.stream.Collectors.toList());

        dtoPage.setRecords(dtoList);
        return dtoPage;
    }



    @Override
    public boolean submitForReview(Long orderId) {
        SalesOrder order = getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 0) {
            throw new RuntimeException("只有草稿状态的订单可以提交审核");
        }

        order.setStatus(1); // 已提交审核
        order.setUpdatedAt(new Date());
        return updateById(order);
    }

    @Override
    @Transactional
    public boolean deleteOrderBatch(List<Long> orderIds) {
        try {
            if (orderIds == null || orderIds.isEmpty()) {
                return false;
            }

            // 先删除订单明细项
            LambdaQueryWrapper<SalesOrderItem> itemWrapper = new LambdaQueryWrapper<>();
            itemWrapper.in(SalesOrderItem::getSoId, orderIds);
            boolean itemsDeleted = salesOrderItemService.remove(itemWrapper);

            if (!itemsDeleted) {
                System.err.println("删除订单明细失败");
                return false;
            }

            // 再删除订单
            boolean ordersDeleted = removeByIds(orderIds);

            if (!ordersDeleted) {
                System.err.println("删除订单失败");
                return false;
            }

            System.out.println("成功删除 " + orderIds.size() + " 个订单及其明细");
            return true;
        } catch (Exception e) {
            System.err.println("删除订单时发生异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("删除订单失败: " + e.getMessage());
        }
    }

    @Override
    public boolean approveOrder(Long orderId, String approvalRemark) {
        SalesOrder order = getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 1) {
            throw new RuntimeException("只有已提交状态的订单可以审核");
        }

        order.setStatus(2); // 审核通过
        order.setUpdatedAt(new Date());
        return updateById(order);
    }

    @Override
    public boolean rejectOrder(Long orderId, String rejectReason) {
        SalesOrder order = getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 1) {
            throw new RuntimeException("只有已提交状态的订单可以拒绝");
        }

        order.setStatus(3); // 审核拒绝
        order.setUpdatedAt(new Date());
        return updateById(order);
    }

    @Override
    @Transactional
    public boolean closeOrder(Long orderId, String closeReason) {
        SalesOrder order = getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        order.setStatus(4); // 已关闭
        order.setUpdatedAt(new Date());
        return updateById(order);
    }

    @Override
    public List<SalesOrder> getOrdersByCustomerId(Long customerId) {
        LambdaQueryWrapper<SalesOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SalesOrder::getCustomerId, customerId);
        wrapper.orderByDesc(SalesOrder::getCreatedAt);
        return list(wrapper);
    }

    @Override
    public String generateOrderCode() {
        String timestamp = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        int random = (int) (Math.random() * 90) + 10;
        return "SO" + timestamp + random;
    }

    @Override
    public IPage<SalesOrderListDTO> getOrderListPage(Integer pageNum, Integer pageSize, String keyword) {
        Page<SalesOrder> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<SalesOrder> wrapper = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.and(w -> w
                .like(SalesOrder::getSoCode, keyword)
            );
        }
        wrapper.orderByDesc(SalesOrder::getCreatedAt);

        IPage<SalesOrder> orderPage = page(page, wrapper);

        // 转换为DTO
        IPage<SalesOrderListDTO> dtoPage = new Page<>(pageNum, pageSize);
        dtoPage.setTotal(orderPage.getTotal());
        dtoPage.setCurrent(orderPage.getCurrent());
        dtoPage.setSize(orderPage.getSize());

        List<SalesOrderListDTO> dtoList = orderPage.getRecords().stream()
            .map(this::convertToOrderListDTO)
            .collect(Collectors.toList());

        dtoPage.setRecords(dtoList);
        return dtoPage;
    }

    @Override
    public List<SalesOrderListDTO> getAllOrderList() {
        List<SalesOrder> orders = list(new LambdaQueryWrapper<SalesOrder>()
            .orderByDesc(SalesOrder::getCreatedAt));

        return orders.stream()
            .map(this::convertToOrderListDTO)
            .collect(Collectors.toList());
    }

    /**
     * 将SalesOrder转换为SalesOrderListDTO
     */
    private SalesOrderListDTO convertToOrderListDTO(SalesOrder order) {
        SalesOrderListDTO dto = new SalesOrderListDTO();
        dto.setId(order.getId());
        dto.setSoCode(order.getSoCode());
        dto.setCustomerId(order.getCustomerId());

        // 获取客户信息
        if (order.getCustomerId() != null) {
            Customer customer = customerService.getById(order.getCustomerId());
            if (customer != null) {
                dto.setCustomerName(customer.getCustomerName());
            }
        }

        dto.setContactPhone(order.getContactPhone());
        dto.setRegion(order.getRegion());
        dto.setSalesRep(order.getSalesRep());
        dto.setRespPhone(order.getRespPhone());
        dto.setSaleDate(order.getSaleDate());
        dto.setExpectedShipDate(order.getExpectedShipDate());
        dto.setStatus(order.getStatus());
        dto.setRemark(order.getRemark());
        dto.setCreatedAt(order.getCreatedAt());
        dto.setUpdatedAt(order.getUpdatedAt());

        // 计算订单金额
        SalesOrderDTO orderDTO = getSalesOrderDetail(order.getId());
        if (orderDTO != null) {
            dto.setTotalAmount(orderDTO.getTotalAmount());
            // 实收金额和未收金额暂时设为0，后续可以从应收账款表获取
            dto.setReceivedAmount(BigDecimal.ZERO);
            dto.setOutstandingAmount(orderDTO.getTotalAmount());
        }

        return dto;
    }

    @Override
    public void calculateOrderAmount(SalesOrderDTO salesOrderDTO) {
        if (salesOrderDTO.getItems() == null || salesOrderDTO.getItems().isEmpty()) {
            salesOrderDTO.setTotalAmount(BigDecimal.ZERO);
            salesOrderDTO.setTotalQuantity(BigDecimal.ZERO);
            return;
        }

        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalQuantity = BigDecimal.ZERO;

        for (SalesOrderItem item : salesOrderDTO.getItems()) {
            BigDecimal qty = item.getQty() == null ? BigDecimal.ZERO : item.getQty();
            BigDecimal price = item.getPrice() == null ? BigDecimal.ZERO : item.getPrice();
            BigDecimal taxRate = item.getTaxRate() == null ? BigDecimal.ZERO : item.getTaxRate();

            // 计算行金额：qty * price * (1 + taxRate/100)
            BigDecimal lineAmount = qty.multiply(price).multiply(BigDecimal.ONE.add(taxRate.divide(new BigDecimal("100"), 4, java.math.RoundingMode.HALF_UP)));
            item.setAmount(lineAmount);

            totalAmount = totalAmount.add(lineAmount);
            totalQuantity = totalQuantity.add(qty);
        }

        salesOrderDTO.setTotalAmount(totalAmount);
        salesOrderDTO.setTotalQuantity(totalQuantity);

        System.out.println("订单金额计算完成 - 总金额: " + totalAmount + ", 总数量: " + totalQuantity);
    }

    /**
     * 处理临时SKU ID，如果是临时ID则自动创建SKU
     * @param item 订单明细项
     * @param salesOrderDTO 销售订单DTO
     * @return 真实的SKU ID，如果不需要处理则返回null
     */
    private Long processTempSkuId(SalesOrderItem item, SalesOrderDTO salesOrderDTO) {
        System.out.println("=== 开始处理临时SKU ID ===");
        System.out.println("订单明细项: " + item);

        // 检查是否是临时SKU ID（格式：temp_数字）
        if (item.getSkuId() == null) {
            System.out.println("SKU ID为空，无需处理");
            return null;
        }

        String skuIdStr = item.getSkuId();
        System.out.println("SKU ID字符串: " + skuIdStr);

        if (!skuIdStr.startsWith("temp_")) {
            System.out.println("不是临时ID格式，尝试转换为Long类型");
            try {
                // 如果不是临时ID，尝试转换为Long类型
                return Long.parseLong(skuIdStr);
            } catch (NumberFormatException e) {
                System.err.println("SKU ID不是有效的数字格式: " + skuIdStr);
                return null;
            }
        }

        try {
            // 提取商品ID
            String productIdStr = skuIdStr.substring(5); // 去掉"temp_"前缀
            Long productId = Long.parseLong(productIdStr);
            System.out.println("从临时ID提取的商品ID: " + productId);

            // 优先使用item中的productId，如果没有则使用从临时ID中提取的
            Long finalProductId = item.getProductId() != null ? item.getProductId() : productId;
            System.out.println("最终使用的商品ID: " + finalProductId);

            // 确保item中的productId被设置
            if (item.getProductId() == null) {
                item.setProductId(finalProductId);
                System.out.println("设置item的productId: " + finalProductId);
            }

            // 检查是否已经存在该商品的SKU
            System.out.println("检查是否已存在该商品的SKU...");
            List<Sku> existingSkus = skuService.list(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProductId, finalProductId)
                .eq(Sku::getStatus, 1));

            System.out.println("查询到的现有SKU数量: " + existingSkus.size());

            if (!existingSkus.isEmpty()) {
                // 如果已存在SKU，返回第一个可用的
                Sku existingSku = existingSkus.get(0);
                System.out.println("找到现有SKU，ID: " + existingSku.getId() + ", 编码: " + existingSku.getSkuCode());
                return existingSku.getId();
            }

            // 创建新的SKU
            System.out.println("开始创建新的SKU...");
            Sku newSku = new Sku();
            newSku.setProductId(finalProductId);
            newSku.setSkuCode("AUTO_" + System.currentTimeMillis()); // 自动生成SKU编码
            newSku.setUnitId(1L); // 默认单位ID
            newSku.setConversionRate(BigDecimal.ONE); // 默认换算率
            newSku.setStatus(1); // 启用状态
            newSku.setCreatedAt(new Date());
            newSku.setUpdatedAt(new Date());

            System.out.println("新SKU对象: " + newSku);

            // 保存SKU
            System.out.println("保存新SKU到数据库...");
            boolean skuSaved = skuService.save(newSku);
            System.out.println("SKU保存结果: " + skuSaved + ", 新SKU ID: " + newSku.getId());

            if (!skuSaved || newSku.getId() == null) {
                throw new RuntimeException("SKU保存失败");
            }

            System.out.println("=== 临时SKU ID处理完成 ===");
            return newSku.getId();

        } catch (Exception e) {
            System.err.println("处理临时SKU ID失败: " + skuIdStr + ", 错误: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("处理临时SKU ID失败: " + skuIdStr, e);
        }
    }

    @Override
    public byte[] generateBatchPrintPDF(List<SalesOrder> orders) {
        try {
            // 使用PDFBox生成PDF
            PDDocument document = new PDDocument();

            // 创建页面
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            // 创建内容流
            PDPageContentStream contentStream = new PDPageContentStream(document, page);

            // 设置字体
            PDFont font = PDType1Font.HELVETICA_BOLD;
            PDFont normalFont = PDType1Font.HELVETICA;

            // 设置标题
            contentStream.beginText();
            contentStream.setFont(font, 18);
            contentStream.newLineAtOffset(50, 750);
            contentStream.showText("销售订单打印报告");
            contentStream.endText();

            // 设置基本信息
            contentStream.beginText();
            contentStream.setFont(normalFont, 12);
            contentStream.newLineAtOffset(50, 720);
            contentStream.showText("打印时间: " + new Date());
            contentStream.newLineAtOffset(0, -20);
            contentStream.showText("订单数量: " + orders.size() + " 个");
            contentStream.endText();

            // 设置表格标题
            contentStream.beginText();
            contentStream.setFont(font, 14);
            contentStream.newLineAtOffset(50, 670);
            contentStream.showText("订单列表");
            contentStream.endText();

            // 绘制表格
            float y = 640;
            float x = 50;
            float lineHeight = 20;

            // 表头
            contentStream.beginText();
            contentStream.setFont(font, 10);
            contentStream.newLineAtOffset(x, y);
            contentStream.showText("订单编号");
            contentStream.newLineAtOffset(120, 0);
            contentStream.showText("客户ID");
            contentStream.newLineAtOffset(80, 0);
            contentStream.showText("订单金额");
            contentStream.newLineAtOffset(80, 0);
            contentStream.showText("订单状态");
            contentStream.newLineAtOffset(80, 0);
            contentStream.showText("创建时间");
            contentStream.endText();

            y -= lineHeight;

            // 绘制分隔线
            contentStream.setLineWidth(1);
            contentStream.moveTo(x, y);
            contentStream.lineTo(x + 450, y);
            contentStream.stroke();

            // 订单数据
            contentStream.beginText();
            contentStream.setFont(normalFont, 9);

            for (SalesOrder order : orders) {
                if (y < 100) {
                    // 如果页面空间不足，创建新页面
                    contentStream.endText();
                    contentStream.close();

                    page = new PDPage(PDRectangle.A4);
                    document.addPage(page);
                    contentStream = new PDPageContentStream(document, page);
                    y = 750;
                }

                contentStream.newLineAtOffset(x, y);
                contentStream.showText(order.getSoCode() != null ? filterNonAscii(order.getSoCode()) : "N/A");
                contentStream.newLineAtOffset(120, 0);
                contentStream.showText(String.valueOf(order.getCustomerId()));
                contentStream.newLineAtOffset(80, 0);
                contentStream.showText("0"); // 订单金额需要从明细计算，暂时显示0
                contentStream.newLineAtOffset(80, 0);
                contentStream.showText(getStatusText(order.getStatus()));
                contentStream.newLineAtOffset(80, 0);
                contentStream.showText(order.getCreatedAt() != null ? order.getCreatedAt().toString() : "N/A");

                y -= lineHeight;
            }

            contentStream.endText();

            // 关闭内容流
            contentStream.close();

            // 将PDF转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.save(baos);
            document.close();

            return baos.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成PDF失败: " + e.getMessage(), e);
        }
    }

    @Override
    public byte[] generateSingleOrderPDF(SalesOrder order) {
        try {
            // 使用PDFBox生成PDF
            PDDocument document = new PDDocument();

            // 创建页面
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            // 创建内容流
            PDPageContentStream contentStream = new PDPageContentStream(document, page);

            // 设置字体
            PDFont font = PDType1Font.HELVETICA_BOLD;
            PDFont normalFont = PDType1Font.HELVETICA;

            // 设置标题
            contentStream.beginText();
            contentStream.setFont(font, 20);
            contentStream.newLineAtOffset(50, 750);
            contentStream.showText("Sales Order");
            contentStream.endText();

            // 订单基本信息
            float y = 700;
            float x = 50;
            float lineHeight = 25;

            contentStream.beginText();
            contentStream.setFont(font, 12);
            contentStream.newLineAtOffset(x, y);
            contentStream.showText("Order ID: " + (order.getSoCode() != null ? order.getSoCode() : "N/A"));
            contentStream.newLineAtOffset(0, -lineHeight);
            contentStream.showText("Customer ID: " + order.getCustomerId());
            contentStream.newLineAtOffset(0, -lineHeight);
            contentStream.showText("Status: " + getStatusText(order.getStatus()));
            contentStream.newLineAtOffset(0, -lineHeight);
            contentStream.showText("Created: " + (order.getCreatedAt() != null ? order.getCreatedAt().toString() : "N/A"));
            contentStream.newLineAtOffset(0, -lineHeight);
            contentStream.showText("Contact Phone: " + (order.getContactPhone() != null ? filterNonAscii(order.getContactPhone()) : "N/A"));
            contentStream.newLineAtOffset(0, -lineHeight);
            contentStream.showText("Region: " + (order.getRegion() != null ? filterNonAscii(order.getRegion()) : "N/A"));
            contentStream.newLineAtOffset(0, -lineHeight);
            contentStream.showText("Sales Rep: " + (order.getSalesRep() != null ? filterNonAscii(order.getSalesRep()) : "N/A"));
            contentStream.endText();

            // 关闭内容流
            contentStream.close();

            // 将PDF转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.save(baos);
            document.close();

            return baos.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成单个订单PDF失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取订单状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "Unknown";
        switch (status) {
            case 0: return "Draft";
            case 1: return "Submitted";
            case 2: return "Approved";
            case 3: return "Rejected";
            case 4: return "Closed";
            default: return "Unknown";
        }
    }

    /**
     * 过滤非ASCII字符，避免PDF字体问题
     */
    private String filterNonAscii(String text) {
        if (text == null) return "N/A";
        // 只保留ASCII字符（0-127），其他字符替换为空格或问号
        StringBuilder result = new StringBuilder();
        for (char c : text.toCharArray()) {
            if (c < 128) {
                result.append(c);
            } else {
                result.append('?');
            }
        }
        return result.toString();
    }

    /**
     * 计算订单总金额
     */
    private BigDecimal calculateOrderTotalAmount(Long orderId) {
        try {
            // 查询订单明细
            LambdaQueryWrapper<SalesOrderItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SalesOrderItem::getSoId, orderId);
            List<SalesOrderItem> items = salesOrderItemService.list(wrapper);

            // 计算总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (SalesOrderItem item : items) {
                if (item.getAmount() != null) {
                    totalAmount = totalAmount.add(item.getAmount());
                } else if (item.getQty() != null && item.getPrice() != null) {
                    // 如果没有金额，则计算：数量 * 价格
                    BigDecimal qty = item.getQty();
                    BigDecimal price = item.getPrice();
                    totalAmount = totalAmount.add(qty.multiply(price));
                }
            }

            return totalAmount;
        } catch (Exception e) {
            e.printStackTrace();
            return BigDecimal.ZERO;
        }
    }

    @Override
    public List<java.util.Map<String, Object>> searchProducts(String keyword, int pageNo, int pageSize) {
        int offset = (pageNo - 1) * pageSize;
        return baseMapper.searchProducts(keyword, offset, pageSize);
    }

    @Override
    public Long countProducts(String keyword) {
        return baseMapper.countProducts(keyword);
    }

    @Override
    public String getCustomerNameByOrderId(Long orderId) {
        return baseMapper.getCustomerNameByOrderId(orderId);
    }

    @Override
    public Map<String, Object> getOrderInfoById(Long orderId) {
        return baseMapper.getOrderInfoById(orderId);
    }
}




